package br.unicamp.ic.lis.docseaservice.model.queryresult;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbutils.ResultSetHandler;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import br.unicamp.ic.lis.docseaservice.exception.DBException;

/**
 * 
 * @author Joao Savio Ceregatti Longo - joaosavio@gmail.com
 */
public class JSONHandler implements ResultSetHandler<JSONArray> {

	@Override
	public JSONArray handle(ResultSet rs) throws SQLException {
		JSONArray jsonArray = new JSONArray();
		int i = 0;

		while (rs.next()) {
			try {
				JSONObject jsonObject = new JSONObject();
				int columnCount = rs.getMetaData().getColumnCount();
				for (int j = 0; j < columnCount; j++) {
					String key = rs.getMetaData().getColumnName(j + 1);
					Object value = rs.getObject(j + 1);
					jsonObject.put(key, value);
				}
				jsonArray.put(i++, jsonObject);
			} catch (JSONException e) {
				throw new DBException(e);
			}
		}
		return jsonArray;
	}
}
